package edu.hawaii.duedates;

import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * For the Email variable.
 * 
 * @author Creighton Okada
 * @author Ka Hung Phillip Lau
 */
public final class Email {

  /**
   * Generates a email with user's supply TO address and SMTP server.
   * 
   * @param server Name of SMTP server.
   * @param toAddr Name of the email address the email send to.
   * @param body Text that will go into the body of the email.
   * @return True if email is sent, false if cannot be send.
   */
  protected boolean send(String server, String toAddr, String body) {
    Properties prop = new Properties();
    prop.put("mail.smtp.host", server);
    Session session = Session.getInstance(prop, null);

    try {
      Message msg = new MimeMessage(session);
      InternetAddress adminAddress = new InternetAddress("duedates-red-discuss@googlegroups.com");
      InternetAddress[] adminAddressArray = { adminAddress };
      InternetAddress userAddress = new InternetAddress(toAddr);

      msg.setFrom(adminAddress);
      msg.setReplyTo(adminAddressArray);
      msg.setRecipient(Message.RecipientType.TO, userAddress);
      msg.setSubject("DueDates: Books Checked Out");
      msg.setSentDate(new Date());
      msg.setText(body);
      Transport.send(msg);

      return true;
    }
    catch (MessagingException mex) {
      System.out.println("Mail failure to: " + toAddr + "\n" + mex);
      return false;
    }

  }

}
